import fetch from 'isomorphic-unfetch';
import qs from 'query-string';
import { filterObject } from './utils';

// initial fetch
const nextFetch = Object.create(null);
// browser support methods
// ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PATCH', 'PUT']
const HTTP_METHOD = ['get', 'post', 'put', 'patch', 'delete', 'getH'];
// can send data method
const CAN_SEND_METHOD = ['post', 'put', 'delete', 'patch'];
const NO_JSON = ['getH', 'get'];

HTTP_METHOD.forEach(method => {
  // is can send data in opt.body
  const canSend = CAN_SEND_METHOD.includes(method);
  const noJson = NO_JSON.includes(method);
  let methodName = method
  if (noJson) {
    methodName = 'get'
  }
  nextFetch[method] = (path, {data, query, header, timeout = 5000} = {}) => {
    let url = path;
    const opts = {
      method: methodName,
      credentials: 'omit',
      headers: {
        ...header
      },
      timeout
    };

    if (query) {
      url += `${url.includes('?') ? '&' : '?'}${qs.stringify(
        filterObject(query, Boolean),
      )}`;
    }

    if (canSend && data) {
      // opts.body = qs.stringify(filterObject(data, Boolean));
      opts.body = data;
    }
    // console.log('opts:', opts)

    console.info('Request Url:', url);
    if (noJson) {
      return fetch(url, opts)
        .then(res => res.text());
    } else {
      return fetch(url, opts)
        .then(res => {
          // console.log('res', res)
          return res.json()
        })
        .then(result => {
          // console.log('result', result)
          return result;
        });
    }
  };
});

export default nextFetch;
